interface Params {
    [key: string]: string | number | boolean;
}

/**
 * Url拼接
 * @param path 目标路径
 * @param query 携带参数
 * @returns 拼接后的url
 */
function $urlJoin(path: string, query?: Params) {
    if (query === undefined) {
        return path
    }

    var url = path + '?' + Object.keys(query).map(key => {
        if (query[key] === null) {
            return ''
        } else {
            return key + '=' + query[key]
        }
    }).join('&')

    return url
}


/**
 * 检查是否是tab页, 是的话使用switchTab并返回true, 否则返回false
 * @param url 
 * @returns 
 */
function checkTabUrl(url: string): boolean {
    if (url.startsWith('/pages/tabs') || url == '/') {
        uni.switchTab({
            url
        })
        return true
    }
    return false
}

/**
 * 打开页面
 * @param path 目标路径
 * @param query 携带参数
 */
function open(call: Function, path: string, query?: Params){
    var url = $urlJoin(path, query)
    if (checkTabUrl(url)) {
        return
    } else {
        call({
            url
        })
    }
}


function push(path: string, query?: Params) {
    open(uni.navigateTo, path, query)
}

function replace(path: string, query?: Params) {
    open(uni.redirectTo, path, query)
}

function back(delta?:number) {
    uni.navigateBack({
        delta
    })
}

function go(delta:number) {
    if (delta > 0) {
        return
    } else {
        uni.navigateBack({
            delta: -delta
        })
    }
}

export default {
    push,
    replace,
    back,
    go
}

// export const routerToGoodsDetail = (id: string) => {
//     .push('/pages/goods-detail/index?id=' + id)
// }
